<template>
  <div>
    <el-page-header :content='``' @back='back()' />
    <div>
      <h2>{{ $t('batch.batch_operation_detail_title') }}</h2>
      <p
        class='title-second mlem-18'
        style='color: #777777'
      >{{ $t('batch.cmd_type') }}: {{ cmdTypeFilter(batchOperation.cmdTypeCode) }}</p>
      <p
        v-if="batchOperation.appName !== undefined && batchOperation.appName !== ''&& batchOperation.appName !== null"
        class='title-second mlem-18'
        style='color: #777777'
      >{{ $t('batch.app_name') }}: {{ batchOperation.appName }}</p>
      <p
        v-if="batchOperation.otaName !== undefined && batchOperation.otaName !== ''&& batchOperation.otaName !== null"
        class='title-second mlem-18'
        style='color: #777777'
      >{{ $t('batch.model') }}: {{ batchOperation.otaName }}</p>
      <p
        v-if="batchOperation.version !== undefined && batchOperation.version !== ''&& batchOperation.version !== null"
        class='title-second mlem-18'
        style='color: #777777'
      >{{ $t('batch.version') }}: {{ batchOperation.version }}</p>
      <p
        v-if="batchOperation.expireTime !== undefined && batchOperation.expireTime !== ''&& batchOperation.expireTime !== null"
        class='title-second mlem-18'
        style='color: #777777'
      >{{ $t('batch.expire_time') }}: {{ dateTimeFilter(batchOperation.expireTime) }}</p>
      <p
        v-if="batchOperation.cmdTypeCode === 'D5'"
        class='title-second mlem-18'
        style='color: #777777'
      >{{ $t('batch.fly_key_cert_download.download_type') }}: {{ $t(batchOperation.flyKeyCertDownloadMethod)
        }} </p>
      <p
        v-if="batchOperation.cmdTypeCode === 'D5'"
        class='title-second mlem-18'
        style='color: #777777'
      >{{ $t('batch.fly_key_cert_download.download_url') }}: {{ batchOperation.flyKeyCertDownloadUrl }} </p>
      <p
        v-if="batchOperation.cmdTypeCode === 'D6'"
        class='title-second mlem-18'
        style='color: #777777'
      >{{ $t('batch.system_parameter.configure_parameters') }}: {{ batchOperation.sysParam }} </p>
      <p
        v-if="batchOperation.cmdTypeCode !== 'D5' && batchOperation.cmdTypeCode !== 'D6'"
        class='title-second mlem-18'
        style='color: #777777'
      >{{ $t('batch.remark') }}: {{ batchOperation.remark }}</p>
      <p
        class='title-second mlem-18'
        style='color: #777777'
      >{{ $t('batch.statistic') }}: {{ $t('batch.total') }}:{{ batchOperation.devNum
        }}/{{ $t('batch.successed') }}:{{ batchOperation.succNum }}</p>
      <p
        v-if='batchOperation.status === 2'
        class='title-second mlem-18'
        style='color: #777777'
      >{{ $t('batch.finished_time') }}:{{ dateTimeFilter(batchOperation.updTime) }}</p>
      <div style='position: absolute;top: 90px;right: 50px;'>
        <el-button
          type='danger'
          v-if="batchOperation.status !== 2 && (batchOperation.cmdTypeCode ==='A2'|| batchOperation.cmdTypeCode==='AB' || batchOperation.cmdTypeCode === 'D6') && verifyPermission('10400008.MANAGE')"
          @click='pauseCommand()'
        ><svg-icon icon-class="VideoPause"/>
          {{ $t('batch.cancel') }}
        </el-button>
        <el-button
          v-if="batchOperation.cmdTypeCode === 'D1'"
          type='primary'
          @click='setttingsDetail'
        >{{ $t('common.history') }}
        </el-button>
      </div>

    </div>

    <el-card
      shadow='never'
      :body-style="{padding: '0px'}"
      :page-size='pageSize'
      :total='totalPage'
      :current-page='pageNo'
      @current-change='currentChangeHandle'
    >
        <el-form class="p-4" @submit.prevent.native inline>
          <el-form-item>
            <el-input
              v-model.trim='dataForm.devSn'
              maxlength='30'
              :placeholder="$t('batch.dev_sn')"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-select
              v-model='dataForm.cmdStatus'
              :placeholder="$t('batch.cmd_status')"
              clearable
            >
              <el-option
                v-for='type in cmdStatusList'
                :key='type.val'
                :label='type.name'
                :value='type.val'
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button
              type='primary'
              class='w-8'
              @click='fetchData(pageNo = 1)'
            ><svg-icon icon-class='Search' /></el-button>
            <!-- <el-button type='primary' class='add-button' @click='addCmdHandle()' size='small'>
              Add
            </el-button>-->
          </el-form-item>
          <el-form-item>
            <el-button type='primary' class='w-8' @click='doExport'>
              <svg-icon icon-class='Download' />
            </el-button>
          </el-form-item>
        </el-form>
      <el-table v-loading='listLoading' :data='tableData' stripe>
        <!--'Command type', 'Number of Terminal', 'Number of Success', 'Create Time', 'Content', 'Remark' -->
        <el-table-column :label="$t('batch.dev_sn')" prop='devSn' />
        <el-table-column :label="$t('batch.cmd_status')" prop='cmdStatus'>
          <template v-slot="{row}">
            <div>
              <span>{{ cmdStatusFilter(row.cmdStatus) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="$t('batch.error_msg')" prop='errMsg'>
          <template v-slot="{row}">
            <div>
              <span>{{ cmdErrMsgFilter(row) }}</span>
            </div>
          </template>
        </el-table-column>
        <!--        <el-table-column-->
        <!--          align='left'-->
        <!--          width='50'-->
        <!--        >-->
        <!--          <template v-slot="scope">-->
        <!--            <i class='el-icon-video-pause' v-if='scope.row.cmdStatus!=' @click='pauseCommandByDevice(scope.row.devSn)' />-->
        <!--          </template>-->
        <!--        </el-table-column>-->
      </el-table>
      <!-- <div class="pagination-wrapper">
        <el-pagination
          v-if="paginationShow"
          :current-page="pageNo"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="totalPage"
          layout="total, sizes, prev, pager, next, jumper"
          style="margin-top: 15px"
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
        />
      </div> -->

      <!-- <add-cmd v-model='addCmdVisible' @close='addCmdVisible = false' @refreshDataList='fetchData'></add-cmd> -->
    </el-card>
  </div>
</template>

<script>
import { verifyBtnPermission } from '@/utils'
import { cmd2DevicePage, cmdInfo, pauseCommand, pauseCommandByDevice, exportCmd2Device } from '@/api/batch'
// import AddCmd from './add-cmd'
import { dateTimeFilter } from '@/filters'
import { getToken } from '@/utils/auth'
import store from '@/store'
import axios from 'axios'

export default {
  components: {
    // AddCmd
  },
  data() {
    return {
      dataForm: {
        devSn: '',
        cmdStatus: ''
      },
      batchOperation: {
        remark: '1234444',
        cmdTypeCode: 'A1',
        devCount: '1',
        succNum: 0,
        paramSetting: {},
        flyKeyCertDownloadMethod: '',
        flyKeyCertDownloadUrl: ''
      },
      paginationShow: true,
      succPercent: 0,
      cmdCode: '',
      totalPage: 0,
      // addCmdVisible: false,
      pageNo: 1,
      pageSize: 10,
      seletedData: [],
      listLoading: false,
      tableData: [],
      filters: [
        'Command type',
        'Number of Terminal',
        'Number of Success',
        'Create Time',
        'Content',
        'Remark'
      ],
      selectedMerchant: '',
      headers: [
        'Command type',
        'Number of Terminal',
        'Number of Success',
        'Create Time',
        'Content',
        'Remark'
      ]
    }
  },
  computed: {
    cmdStatusList() {
      return this.$t('batch.statusList')
    }
  },
  mounted() {
    this.cmdCode = this.$route.params.operationKeyId
    // this.batchOperation = this.$route.params.batchOperation
    // alert(JSON.stringify(this.batchOperation))
    this.init()
    this.fetchData()
  },
  methods: {
    dateTimeFilter,
    verifyPermission(val){
      return verifyBtnPermission(val)
    },
    cmdStatusFilter(status) {
      const statusList = this.$t('batch.statusList')
      for (var i = 0; i < statusList.length; i++) {
        var statusObj = statusList[i]
        if (status === statusObj.val) {
          return statusObj.name
        }
      }
      // statusList.array.forEach(statusObj => {
      //   alert(JSON.stringify(statusObj))
      //   if (status === statusObj.val) {
      //
      //     alert(1)
      //     return statusObj.name
      //   }
      // })
      // const statusMap = {
      //   0: this.$t('terminal.status.waiting_push'),
      //   1: this.$t('terminal.status.pushing'),
      //   2: this.$t('terminal.status.executing'),
      //   3: this.$t('terminal.status.push_fail'),
      //   4: this.$t('terminal.status.pause'),
      //   5: this.$t('terminal.status.exec_succ'),
      //   6: this.$t('terminal.status.exec_fail'),
      //   7: this.$t('terminal.status.waiting_ack'),
      //   8: this.$t('terminal.status.term_offline'),
      //   9: this.$t('terminal.status.cmd_timeout')
      // }
      // return statusMap[status]
    },
    cmdErrMsgFilter(res) {
      if (res.cmdStatus === 10) {
        // 取消的指令显示撤销的cmdCode
        if (res.errMsg) {
          try {
            let msg = JSON.parse(res.errMsg)
            if (msg) {
              return msg.originalCmdCode
            }
          } catch (e) {
            return res.errMsg
          }
        }
      } else {
        if (res.errMsg && res.errMsg.length >= 7) {
          let reg = new RegExp(/^[0-9a-fA-F]{6}\|$/)
          if (res.errMsg.indexOf('&') !== -1) {
            let msgArr = res.errMsg.split('&')
            let msgInfo = ''
            msgArr.forEach((item) => {
              let prefixCode = item.substr(0, 7)
              if (reg.test(prefixCode)) {
                if (msgInfo) {
                  msgInfo = msgInfo + ','
                }
                msgInfo = msgInfo + this.getCmdErrorMsg(prefixCode.substr(0, 6))
              }
            })
            return msgInfo
          } else {
            let prefixCode = res.errMsg.substr(0, 7)
            if (reg.test(prefixCode)) {
              return this.getCmdErrorMsg(prefixCode.substr(0, 6))
            }
          }
        }
      }
    },
    getCmdErrorMsg(code) {
      return this.$t('batch.cmd_error.' + code)
    },
    cmdTypeFilter(cmdTypeCode) {
      const cmdTypeMap = {
        A0: this.$t('command.desc.A0'),
        A1: this.$t('command.desc.A1'),
        A2: this.$t('command.desc.A2'),
        A3: this.$t('command.desc.A3'),
        A4: this.$t('command.desc.A4'),
        A5: this.$t('command.desc.A5'),
        A6: this.$t('command.desc.A6'),
        A7: this.$t('command.desc.A7'),
        A8: this.$t('command.desc.A8'),
        A9: this.$t('command.desc.A9'),
        AA: this.$t('command.desc.AA'),
        AB: this.$t('command.desc.AB'),
        AC: this.$t('command.desc.AC'),
        AD: this.$t('command.desc.AD'),
        B1: this.$t('command.desc.B1'),
        B2: this.$t('command.desc.B2'),
        B3: this.$t('command.desc.B3'),
        B4: this.$t('command.desc.B4'),
        B5: this.$t('command.desc.B5'),
        B6: this.$t('command.desc.B6'),
        B8: this.$t('command.desc.B8'),
        B9: this.$t('command.desc.B9'),
        BA: this.$t('command.desc.BA'),
        BB: this.$t('command.desc.BB'),
        D0: this.$t('command.desc.D0'),
        D1: this.$t('command.desc.D1'),
        D2: this.$t('command.desc.D2'),
        D5: this.$t('command.desc.D5'),
        D6: this.$t('command.desc.D6')
      }
      return cmdTypeMap[cmdTypeCode]
    },
    // init(operationKeyId) {
    //   this.cmdCode = operationKeyId
    // },
    setttingsDetail() {
      this.$router.push({
        name: 'settingsDetail',
        params: this.batchOperation.paramSetting
      })
    },
    back() {
      // this.$router.query.activeName = 'task'
      this.$router.back(-1)
    },
    init() {
      cmdInfo(this.cmdCode).then((res) => {
        this.batchOperation = res
        if (this.batchOperation.flyKeyCertDownloadMethod) {
          if ('0' == this.batchOperation.flyKeyCertDownloadMethod) {
            this.batchOperation.flyKeyCertDownloadMethod = 'batch.fly_key_cert_download.download_methods.normal'
          } else if ('1' == this.batchOperation.flyKeyCertDownloadMethod) {
            this.batchOperation.flyKeyCertDownloadMethod = 'batch.fly_key_cert_download.download_methods.auto'
          }
        }
      })
    },
    fetchData() {
      this.listLoading = true
      const params = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        devSn: this.dataForm.devSn,
        cmdStatus: this.dataForm.cmdStatus
      }
      console.log(params)
      cmd2DevicePage(this.cmdCode, params).then((res) => {
        this.listLoading = false
        this.tableData = res.data
        this.totalPage = res.rows
      })
    },
    dateTimeFilter(value) {
      return dateTimeFilter(value)
    },
    formatDate(row, column, cellValue, index) {
      return dateTimeFilter(cellValue)
    },
    handleSelectionChange(val) {
      this.seletedData = val
    },
    sizeChangeHandle(val) {
      this.pageSize = val
      this.fetchData()
    },
    currentChangeHandle(val) {
      this.pageNo = val
      this.fetchData()
    },
    showHeader(label) {
      return this.headers.includes(label)
    },
    pauseCommand() {
      this.$commonConfirm().showConfirmDialog(this.$t('page.tip'), this.$t('batch.pause_whole_task_tip'), this.$t('common.confirm'), (instance, done) => {
        instance.loading = true
        pauseCommand(this.cmdCode).then((res) => {
          this.$message.success(this.$t('common.message.operation_success'))
        }).catch(
          this.$confirmError
        ).finally(() => {
          this.$commonConfirm().close()
          instance.loading = false
          this.init()
          this.fetchData()
        })
      })
    },
    pauseCommandByDevice(devSn) {
      this.$commonConfirm().showConfirmDialog(this.$t('page.tip'), this.$t('batch.pause_device_task_tip'), this.$t('common.confirm'), (instance, done) => {
        instance.loading = true
        pauseCommandByDevice(this.cmdCode, devSn).then((res) => {
          this.$message.success(this.$t('common.message.operation_success'))
        }).catch(this.$confirmError)
          .finally(() => {
            instance.loading = false
          })
      })
    },
    doExport() {
      let params = {
        devSn: this.dataForm.devSn,
        cmdStatus: this.dataForm.cmdStatus,
        timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
      }
      this.$confirm(
        this.$t('batch.download_cmd_devices_tip'),
        this.$t('common.tips'),
        {
          confirmButtonText: this.$t('page.confirm'),
          cancelButtonText: this.$t('page.cancel'),
          type: 'warning'
        })
        .then(() => {
          axios({
            method: 'get',
            url: import.meta.env.VITE_APP_BASE_API + `/online/management/admin/batch/command/${this.cmdCode}/devices/export`,
            responseType: 'blob',
            headers: {
              'WEB-TOKEN': getToken(),
              LANG:
                localStorage.getItem(store.state.user.keys.storage.lang) || 'en-US'
            },
            params: params
          })
            .then(res => {
              let data = res.data
              if (data) {
                let dis = res.headers['content-disposition']
                if (dis) {
                  let fileName = dis.split('attachment;filename=')[1]
                  let url = window.URL.createObjectURL(data)
                  let a = document.createElement('a')
                  a.href = url
                  a.download = fileName
                  a.click()
                } else {
                  this.$message.success(this.$t('common.export_processing'))
                  this.$store.dispatch('app/fetchTaskData')
                }
              } else {
                this.$message.error(this.$t('common.export_error'))
              }
            })
            .catch((e) => {
              this.$confirmError(e)
            })
          // this.$store.commit('app/OPEN_TASK_PROGRESS')
        })
    },
    downLoad(url, params) {
      axios({
        method: 'get',
        url: url,
        responseType: 'blob',
        headers: {
          'WEB-TOKEN': getToken(),
          'LANG': localStorage.getItem(store.state.user.keys.storage.lang) || 'en-US'
        },
        params: params
      }).then(res => {
        let data = res.data
        if (data) {
          let dis = res.headers['content-disposition']
          let fileName = dis.split('attachment;filename=')[1]
          var url = window.URL.createObjectURL(data)
          var a = document.createElement('a')
          a.href = url
          a.download = fileName
          a.click()
        } else {
          this.$message.error(this.$t('common.export_error'))
        }
        // this.dataListLoading = false
      }).catch(this.$confirmError)
    }
  }
}
</script>

<style lang='scss'>
</style>

<style lang='scss' scoped>
.query-button {
  margin-left: 30px;
}

.svg-container {
  cursor: pointer;
  margin-top: 6px;
  margin-left: 20px;
  font-size: 24px;
  display: inline-block;
}

.pagination-wrapper {
  text-align: right;
}
</style>
